package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"

	"golang.org/x/net/html"
)

func main() {

	//只处理指定域名下面的链接
	baseURL, _ := url.Parse("http://golang.org")
	if !strings.HasPrefix(link, baseURL.Host) {
		//跳过外部链接
		continue
	}
	//

}

func downloadPage(url string) ([]byte, error) {
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println(err)
		return []byte{}, nil
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return []byte{}, nil
	}
	return body, nil
}

func rewriteLinks(htmlContent []byte, baseURL string) []byte {
	doc, _ := html.Parse(bytes.NewReader(htmlContent))
	var f func(*html.Node)
	f = func(n *html.Node) {
		if n.Type == html.ElementNode {
			//处理不同标签的属性
			switch n.Data {
			case "a", "link":
				rewriteAttr(n, "href", baseURL)
			case "img", "script":
				rewriteAttr(n, "src", baseURL)
			}
		}

		for c := n.FirstChild; c != nil; c = c.Nextsibling {
			f(c)
		}

	}
	f(doc)

	var buf bytes.Buffer
	html.Reader(&buf, doc)
	return buf.Bytes()
}

func rewriteAttr(n *html.Node, attrName string, baseURL string) {
	for i, a := range n.Attr {
		if a.Key == attrName {
			if strings.HasPrefix(a.Val, baseURL) {
				relativePath := strings.TrimPrefix(a.Val, baseURL)
				n.Attr[i].Val = "./" + relativePath
			}
			break
		}
	}
}
